<template>
  <sys-dialog :visible.sync="openDialog" :left="0" :bottom="0" width="100%" height="80%" animation-name="bottom" @close="close">
    <template slot-scope="scope">
      <goods-model v-if="scope.isShow" :goods="goods" :type="type" :buy-record="buyRecord" @close-dialog="closeDialog" @ensure="ensure"></goods-model>
    </template>
  </sys-dialog>
</template>

<script>
  import SystemUtil from 'utils/systemUtil';

  import SysDialog from 'common/sysDialog';
  import GoodsModel from './goodsModel';

  import ShopMallApi from 'services/shopMallApi';

  import storeMixins from 'mixins/storeMixins';

  export default {
    mixins: [storeMixins],
    
    props: {
      visible: {
        type: Boolean,
        required: true
      },
      goods: {
        type: Object,
        required: true
      },
      type: {
        type: String,
        default: 'shopCar'
      },
      buyRecord: Object
    },

    watch: {
      visible() {
        this.openDialog = this.visible;
      }
    },

    data() {
      return {
        openDialog: this.visible
      };
    },

    methods: {
      closeDialog() {
        this.$emit('update:visible', false);
      },

      ensure(goodsModelData) {
        let type = this.type;
        if (type === 'shopCar') {
          this.goodsToCar(goodsModelData);
        } else if (type === 'preBuy') {
          this.preBuy(goodsModelData);
        } else {
          this.buyNow(goodsModelData);
        }
      },

      goodsToCar(goodsModelData) {
        SystemUtil.showLoading('加入购物车');
        ShopMallApi.goodsToCar(goodsModelData).then(res => {
          SystemUtil.hideLoading();
          this.$emit('update:visible', false);
          this.$emit('buy-success', goodsModelData);
          this.$api.showToast({
            title: '成功加入购物车'
          });
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      preBuy(goodsModelData) {
        SystemUtil.showLoading('商品记录');
        ShopMallApi.preBuy(goodsModelData).then(res => {
          SystemUtil.hideLoading();
          this.$emit('update:visible', false);
          this.$emit('buy-success', goodsModelData);
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      buyNow(goodsModelData) {
        SystemUtil.showLoading('');
        ShopMallApi.buyGoods(goodsModelData, this.location.lnglat).then(orderId => {
          SystemUtil.hideLoading();
          this.$emit('update:visible', false);
          this.$emit('buy-success', goodsModelData, orderId);
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      close() {
        this.$emit('close');
      }
    },

    components: {
      SysDialog,
      GoodsModel
    }
  };

</script>
